package com.craftplay.service;

import com.alibaba.fastjson.JSONObject;
import com.craftplay.common.PageBean;
import com.craftplay.dao.BehaveMapper;
import com.craftplay.dao.UnitMapper;
import com.craftplay.dao.UserMapper;
import com.craftplay.model.BehaveModel;
import com.craftplay.model.Unit;
import com.craftplay.model.User;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BehaveService {

    @Autowired
    private BehaveMapper behaveMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UnitMapper unitMapper;

    /**
     * 插入行为
     *
     * @param behaveModel
     */
    public void insertBehave(BehaveModel behaveModel) {
        behaveMapper.insert(behaveModel);
    }


    /**
     * 未读消息数量
     *
     * @param userId
     */
    public int getMyUnReadCount(int userId) {
        List<BehaveModel> behaveList = behaveMapper.getBehaveList(userId, 0);
        return behaveList != null ? behaveList.size() : 0;
    }


    /**
     * 获取我的消息
     *
     * @param pageNum
     * @param pageSize
     * @param userId
     * @param isRead
     * @return
     */
    public PageBean<BehaveModel> getBehaveList(int pageNum, int pageSize, Integer userId, Integer isRead) {
        PageHelper.startPage(pageNum, pageSize);
        List<BehaveModel> behaveList = behaveMapper.getBehaveList(userId, isRead);
        for (BehaveModel behaveModel : behaveList) {
            //
            User user = userMapper.selectByPrimaryKey(behaveModel.getBuserId());
            behaveModel.setHead_url(user.getHeadUrl());
            behaveModel.setNickname(user.getNickname());
            if (behaveModel.getUnitId() != null) {
                Unit unit = unitMapper.selectByPrimaryKey(behaveModel.getUnitId());
                if (unit == null || unit.getKind() == null) {
                    behaveList.remove(behaveList);
                    behaveMapper.deleteBehave(behaveModel);
                    continue;
                }
                behaveModel.setKind(unit.getKind());
                //指点跟动态
                if (unit.getKind() == 8 || unit.getKind() == 10) {
                    behaveModel.setTitle(unit.getContent().length() > 20 ? unit.getContent().substring(0, 20) : unit.getContent());
                } else {
                    behaveModel.setTitle(unit.getTitle());
                }
                behaveModel.setTypeId(unit.getTypeId());
            }
            //将消息设为已读
            isRead(behaveModel);
        }
        return new PageBean<>(behaveList);
    }

    /**
     * 将消息设为已读
     *
     * @param behaveModel
     */
    public void isRead(BehaveModel behaveModel) {
        behaveMapper.isRead(behaveModel);
    }


}
